package com.yqg.manage.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yqg.manage.controller.dto.FileDTO;
import com.yqg.manage.controller.dto.UpLoadDTO;
import com.yqg.manage.entity.RelatedFile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yqg.manage.common.Result;
import com.yqg.manage.service.IRelatedFileService;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * RelatedFileController 前端控制器
 *
 * @author suzhuang
 * @since 2023-07-05
 */

@Slf4j
@RestController
@RequestMapping("/related-file")
public class RelatedFileController {

    @Resource
    private IRelatedFileService relatedFileService;

    @Value("${upload.path}")
    private String path;

    @Value("${filename.separator}")
    private String separator;

    /**
     * 新增或者更新
     */
    @PostMapping("/edit")
    public Result save(@RequestBody RelatedFile relatedFile) {
        return Result.success(relatedFileService.saveOrUpdate(relatedFile));
    }

    /**
     * 删除
     */
    @GetMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        RelatedFile relatedFile = relatedFileService.getById(id);
        return Result.success(relatedFileService.removeById(relatedFile));
    }

    /**
     * 查询所有
     */
    @GetMapping("/all")
    public Result findAll() {
        List<RelatedFile> list = relatedFileService.list();
        return Result.success(list);
    }

    /**
     * 根据id查询
     */
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Long id) {
        return Result.success(relatedFileService.getById(id));
    }

    /**
     * 分页查询
     */
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<RelatedFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderBy(true, true, "id");//正序排序
        return Result.success(relatedFileService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    /**
     * 文件上传
     *
     * @param upLoadDTO
     * @return
     * @throws Exception
     */
    @PostMapping("/upload")
    public Result upload(UpLoadDTO upLoadDTO) throws Exception {
        String newPath = relatedFileService.upload(upLoadDTO);
        if (newPath == null) {
            return Result.error();
        }
        return Result.success(newPath);
    }

    /**
     * 文件上传(一个文件)
     *
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/uploadSign")
    public Result uploadSign(MultipartFile file) throws Exception {
        FileDTO fileDTO = relatedFileService.uploadSign(file);
        fileDTO.setId(null);
        if (fileDTO == null) {
            return Result.error();
        }
        return Result.success(fileDTO);
    }

    /**
     * 案件文件列表
     *
     * @return
     */
    @GetMapping("/case/{caseno}")
    public Result byCase(@PathVariable String caseno) {
        RelatedFile[] relatedFiles = relatedFileService.getCaseList(caseno);

        return Result.success(relatedFiles);
    }

    /**
     * 文件下载
     *
     * @return
     */
    @GetMapping("/download")
    public void download(String filePath, HttpServletResponse response) throws IOException {
        // 获得待下载文件所在文件夹的绝对路径
        String file = filePath;
        log.info(file);
        // 获得文件输入流
        FileInputStream inputStream = new FileInputStream(file);
        //提取出上传的文件名
        int index = file.indexOf(separator); // 找到分隔符的索引
        String uploadfilename;
        if (index != -1) {
            int length = path.length();
            uploadfilename = file.substring(length, index) + file.substring(file.lastIndexOf(".")); // 提取分隔符前的部分和文件后缀
        } else {
            uploadfilename = file; // 如果没有分隔符，则结果与原文件名相同
        }
        // 对文件名进行URL编码
        String encodedFileName = URLEncoder.encode(uploadfilename, "UTF-8");
        // 设置响应头、以附件形式打开文件，并修改下载的文件名
        response.setHeader("content-disposition", "attachment; filename=\"" + encodedFileName + "\"");
        ServletOutputStream outputStream = response.getOutputStream();
        int len = 0;
        byte[] data = new byte[1024];
        while ((len = inputStream.read(data)) != -1) {
            outputStream.write(data, 0, len);
        }
        outputStream.close();
        inputStream.close();
    }

    @PostMapping("/uploadPDF")
    public Result uploadPDF(MultipartFile file, @RequestParam Long id ) {
        Boolean b = relatedFileService.uploadPDF(file,id);

        return Result.success(b);
    }
}

